<template>
  <a-modal
    title="新建数据源"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :destroyOnClose="true"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="名称">
          <a-input
            placeholder="名称"
            allow-clear
            v-decorator="['name', { rules: [{ required: true, message: '名称不能为空！' }] }]"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="唯一标识">
          <a-input
            placeholder="唯一编码，不能重复"
            allow-clear
            v-decorator="[
              'code',
              {
                rules: [
                  { required: true, message: '编码不能为空！' },
                  { pattern: new RegExp(/^[a-zA-Z][a-zA-Z0-9]{3,}$/), message: '必须以字母开头,最少4位字符' },
                ],
              },
            ]"
          />
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="ES地址"
          extra="es地址格式：http://127.0.0.1:9210/"
        >
          <a-input
            placeholder="url地址"
            allow-clear
            v-decorator="[
              'url',
              {
                rules: [
                  { required: true, message: 'url地址不能为空！' },
                  {
                    pattern: new RegExp(/^http[s]?:\/\/.*?\/$/),
                    message: '请输入正确的url地址',
                  },
                ],
              },
            ]"
          />
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="使用类型">
          <a-radio-group v-decorator="['useType']">
            <a-radio :value="1"> Master </a-radio>
            <a-radio :value="0"> Slave </a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否使用">
          <a-switch
            v-decorator="['activated', { valuePropName: 'checked' }]"
            checked-children="启用"
            un-checked-children="禁用"
          />
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="登录授权">
          <a-radio-group v-decorator="['isToken']" @change="changeToken">
            <a-radio :value="0"> 无token </a-radio>
            <a-radio :value="1"> 需要token </a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="登录账号" v-if="isToken">
          <a-input
            placeholder="登录账号"
            allow-clear
            autocomplete="new-password"
            v-decorator="['username', { rules: [{ required: true, message: '登录账号不能为空！' }] }]"
          />
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="密码" v-if="isToken">
          <a-input-password
            placeholder="密码"
            autocomplete="new-password"
            v-decorator="['password', { rules: [{ required: true, message: '登录密码不能为空！' }] }]"
          />
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="描述">
          <a-input
            placeholder="描述"
            allow-clear
            v-decorator="['description']"
            :auto-size="{ minRows: 3 }"
            type="textarea"
          />
        </a-form-item>
      </a-form>
    </a-spin>
    <template slot="footer">
      <a-button @click="handleCancel">关闭</a-button>
      <a-button type="primary" @click="handleSubmit">确定</a-button>
    </template>
  </a-modal>
</template>

<script>
import { editDatasource } from '@/api/datasource'
export default {
  name: 'EditDatasourceModal',
  data () {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      visible: false,
      confirmLoading: false,
      // 是否需要token
      isToken: false,
      // es授权信息
      authorization: {},
      form: this.$form.createForm(this),
      mdl: {}
    }
  },

  methods: {
    /**
     * 改变token
     */
    changeToken (e) {
      console.log('radio checked', e.target.value)
      if (this.isToken) {
        this.authorization = this.form.getFieldsValue(['username', 'password'])
        this.isToken = false
      } else {
        this.isToken = true
        this.$nextTick(() => {
          this.form.setFieldsValue({
            username: this.authorization.username,
            password: this.authorization.password
          })
        })
      }
    },

    /**
     * 初始化弹框
     */
    init (record) {
      this.visible = true
      this.isToken = false
      this.mdl = Object.assign({}, record)

      if (this.mdl.isToken) {
        this.isToken = true
        var token = this.parseToken(this.mdl.token)
        this.mdl.username = token[0]
        this.mdl.password = token[1]
      } else {
         this.mdl.username = this.mdl.password = ''
      }
      
      this.$nextTick(() => {
        this.form.setFieldsValue({
          name: this.mdl.name,
          code: this.mdl.code,
          url: this.mdl.url,
          useType: this.mdl.useType,
          activated: this.mdl.switch,
          isToken: this.mdl.isToken,
          username: this.mdl.username,
          password: this.mdl.password,
          description: this.mdl.description
        })
      })
    },

    /**
     * 提交
     */
    handleSubmit () {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          if (values.isToken) {
            values.token = this.getToken(values.username, values.password)
          } else {
            values.token = null
            values.username = null
            values.password = null
          }
          values.activated = values.activated ? 1 : 0
          values.id = this.mdl.id
          console.log('values----', values)
          editDatasource(values).then((res) => {
            if (res) {
              // 存储成功、刷新列表
              this.$emit('ok', values)
              this.visible = false
              this.confirmLoading = false
              this.$notification['success']({
                message: '提示',
                description: '数据修改成功！'
              })
            }
          })
        } else {
          this.confirmLoading = false
        }
      })
    },

    /**
     * 关闭弹框
     */
    handleCancel () {
      this.visible = false
    },

    /**
     * 组装token
     */
    getToken (username, password) {
      return window.btoa(`${username}:${password}`)
    },

    /**
     * 解析token
     */
    parseToken (token) {
      let tokenCache = window.atob(token)
      tokenCache = tokenCache.split(':')
      return tokenCache
    }
    
  }
}
</script>
